package com.xiashitech.apiservice.api;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.xiashitech.apiservice.Constants.ErrorCode;
import com.xiashitech.apiservice.config.AuthConfig;
import com.xiashitech.apiservice.service.IDiagnosisService;
import com.xiashitech.interfaces.agent.dto.diagnosis.CommandReq;
import com.xiashitech.interfaces.agent.dto.diagnosis.CommandResp;
import com.xiashitech.interfaces.apiservice.dto.base.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * agent在线诊断：1、agent获取诊断命令，agent输出诊断结果；2、页面给agent传输诊断命令，将agent输出的诊断结果返回页面。
 */
@Controller
@RequestMapping(value = "/v1/agent")
@RequiredArgsConstructor(onConstructor =@_(@Autowired))
public class DiagnosisController {
    private static final Log log = LogFactory.get();

    private final IDiagnosisService diagnosisService;

    private final AuthConfig authConfig;

    /**
     * agent读取用户输入的诊断命令
     * @param commandReq
     * @return
     */
    @RequestMapping(value = "/getDiagnosisCommand", method = RequestMethod.POST, produces = "application/json;charset=UTF-8" ,consumes = "application/json;charset=UTF-8")
    @ResponseBody
    public CommandResp getDiagnosisCommand(@RequestBody CommandReq commandReq) {
        if(commandReq == null || commandReq.getSystemId() == null || "".equals(commandReq.getSystemId()) || commandReq.getMicroServiceId() == null || "".equals(commandReq.getMicroServiceId())) {
            return CommandResp.builder().build();
        }
        CommandResp commandResp = diagnosisService.getAndRemoveDiagnosisCommand(commandReq.getSystemId(), commandReq.getMicroServiceId());
        return commandResp;
    }

    /**
     * agent将诊断结果传输过来并保存在内存队列中
     * @param commandResp
     * @return
     */
    @RequestMapping(value = "/transmitCommandResult", method = RequestMethod.POST, produces = "application/json;charset=UTF-8" ,consumes = "application/json;charset=UTF-8")
    @ResponseBody
    public Response transmitCommandResult(@RequestBody CommandResp commandResp) {
        if(commandResp == null || commandResp.getDiagnosisResult() == null || "".equals(commandResp.getDiagnosisResult())) {
            return new Response(ErrorCode.RESULT_4001.getCode(),ErrorCode.RESULT_4001.getMessage());
        }
        diagnosisService.addCommandResult(commandResp.getSystemId(),commandResp.getMicroServiceId(),commandResp.getLine(),commandResp.getSessionId(),commandResp.getDiagnosisResult());
        return new Response(ErrorCode.RESULT_1001.getCode(),ErrorCode.RESULT_1001.getMessage());
    }

    /**
     * 网页向agent发送命令
     * @param systemId
     * @param microServiceId
     * @param line
     * @param sessionId
     * @return
     */
    @RequestMapping(value = "/dcmd", method = RequestMethod.GET)
    @ResponseBody
    public Response debugCommand(@RequestParam("systemId") String systemId,
                                 @RequestParam("microServiceId") String microServiceId,
                                 @RequestParam("line") String line,
                                 @RequestParam(value = "sessionId",required = false) Integer sessionId) {
        if(systemId == null || microServiceId == null || line == null) {
            return new Response(ErrorCode.RESULT_4001.getCode(),ErrorCode.RESULT_4001.getMessage());
        }
        try {
            diagnosisService.addDiagnosisCommand(systemId,microServiceId,line,sessionId);
        } catch (Exception e) {
            return new Response(ErrorCode.RESULT_4001.getCode(),ErrorCode.RESULT_4001.getMessage()+":"+e.getMessage());
        }
        return new Response(ErrorCode.RESULT_1001.getCode(),ErrorCode.RESULT_1001.getMessage());
    }

    /**
     * 网页获取agent的诊断结果
     * @param systemId
     * @param microServiceId
     * @return
     */
    @RequestMapping(value = "/dresult", method = RequestMethod.GET)
    @ResponseBody
    public List<CommandResp> debugResult(@RequestParam("systemId") String systemId,
                                         @RequestParam("microServiceId") String microServiceId) {
        if(systemId == null || "".equals(systemId) || microServiceId == null || "".equals(microServiceId)) {
            return new ArrayList();
        }
        return diagnosisService.getCommandResults(systemId,microServiceId);
    }

    /**
     * 开启/关闭在线诊断
     * @param systemId
     * @param microServiceId
     * @param onoff: 1开启在线诊断；2关闭在线诊断；
     * @return
     */
    @RequestMapping(value = "/dswitch", method = RequestMethod.GET)
    @ResponseBody
    public Response switchDiagnosis(@RequestParam("systemId") String systemId,
                                    @RequestParam("microServiceId") String microServiceId,
                                    @RequestParam("onoff") Integer onoff) {
        if(systemId == null || microServiceId == null || onoff == null) {
            return new Response(ErrorCode.RESULT_4001.getCode(),ErrorCode.RESULT_4001.getMessage());
        }
        try {
            diagnosisService.switchDiagnosis(systemId,microServiceId,onoff);
        } catch (Exception e) {
            return new Response(ErrorCode.RESULT_4001.getCode(),ErrorCode.RESULT_4001.getMessage()+":"+e.getMessage());
        }
        return new Response(ErrorCode.RESULT_1001.getCode(),ErrorCode.RESULT_1001.getMessage());
    }

    @RequestMapping("/dn")
    public String gotoDebugWeb(@RequestParam("host") String host,Model model) {
        if(authConfig.getDiagnosis() == null || !authConfig.getDiagnosis()) {
            throw new RuntimeException(ErrorCode.RESULT_4001.getMessage());
        }
        model.addAttribute("host", host);
        return "diagnosis";
    }
}
